<!-- 订单界面 -->
<template>
	<!-- tab切换 -->
	<view class="order-tab">
		<view v-for="(item,index) in tab" :key="index" @click="clickTab(index,item.query)">
			<text>{{item.name}}</text>
			<text :class="{'order-select': index == tabIndex}"></text>
		</view>
	</view>
	<view style="height: 60rpx;"></view>

	<!-- 商品订单数据 -->
	<view class="order-back" v-for="(item,index) in order_data" :key="index">
		<!-- 订单编号 -->
		<view class="order-top">
			<text>订单编号：{{item.order_number}}</text>
			<text v-if="item.pay_status == 0">待付款</text>
			<text v-if="item.pay_status == 1 && item.deliver_status == 0 ">待发货</text>
			<text v-if="item.pay_status == 1 && item.deliver_status == 1 ">待收货</text>
			<text v-if="item.pay_status == 1 && item.deliver_status == 2 ">待评价</text>
			<text v-if="item.pay_status == 1 && item.deliver_status == 3 ">待退款</text>
			<text v-if="item.pay_status == 1 && item.deliver_status == 4 ">已退款</text>
		</view>

		<!-- 商品内容部分 -->
		<view class="order-card">
			<!-- 商品图片 -->
			<view>
				<image :src="item.goods_image" mode="aspectFill"></image>
			</view>
			<!-- 商品标题、规格 -->
			<view>
				<text class="order-title-padding">{{item.goods_title}}</text>
				<text class="order-specs" v-for="(item2,index2) in item.specs" :key="index2" v-if="item.specs.length > 0">{{item2.att_val}}</text>
				<text  class="order-specs" v-else>该商品无规格</text>
			</view>
			<!-- 商品价格和数量 -->
			<view>
				<text class="order-title-padding order-num">{{item.goods_price}}</text>
				<text class="order-num">x {{item.buy_amount}}</text>
			</view>
		</view>

		<!-- 合计价格 -->
		<view class="order-total">
			<view class="order-refund" v-if="item.deliver_status==3||item.deliver_status==4">退款理由：{{item.refund_reason}}</view>
			<view class="order-subtotal">
				<text>合计</text>
				<text>￥{{item.subtotal}}</text>
			</view>
		</view>

		<!-- 待发货/申请退款等按钮 -->
		<!-- 待支付的状态 -->
		<view class="order-button" v-if="item.pay_status== 0 ">
			<!-- 取消订单、继续支付 -->
			<text class="order-button-b" @click="cancelOrder(item,index)">取消订单</text>
			<text class="order-button-b" @click="continuePay(item,index)">继续支付</text>
		</view>

		<!-- 支付成功的状态 -->
		<view class="order-button" v-else-if="item.pay_status== 1 ">
			<!-- 1、待发货 申请退款 -->
			<block v-if="item.deliver_status == 0 ">
				<text class="order-button-a">待发货</text>
				<text class="order-button-b" @click="applyRefund(item,index)">申请退款</text>
			</block>
			<!-- 2、确认收货 查看物流 申请退款 -->
			<block v-if="item.deliver_status == 1 ">
				<text class="order-button-a" @click="confirmReceive(item,index)">确认收货</text>
				<text class="order-button-b" @click="goTracking(item)">查看物流</text>
				<text class="order-button-b" @click="applyRefund(item,index)">申请退款</text>
			</block>
			<!-- 3、已发货 评价 申请退款 -->
			<block v-if="item.deliver_status == 2 ">
				<text class="order-button-a">已发货</text>
				<text class="order-button-b" @click="goEavluate(item,index)">{{item.evaluate ? '已评价' : '评价'}}</text>
				<text class="order-button-b" @click="applyRefund(item,index)">申请退款</text>
			</block>
			<!-- 4、申请退款中 -->
			<block v-if="item.deliver_status == 3 ">
				<text class="order-button-b">申请退款中</text>
			</block>
			<!-- 5、退款成功 -->
			<block v-if="item.deliver_status == 4 ">
				<text class="order-button-b">退款成功</text>
			</block>
		</view>

		<!-- 已取消订单的状态 -->
		<view class="order-button" v-else-if="item.pay_status== 2 ">
			<!-- 订单已取消 -->
			<text class="order-button-a">订单已取消</text>
		</view>
	</view>

	<!-- 没有数据的提示 -->
	<view class="tips" v-if="order_data.length == 0">没有订单数据</view>

	<!-- 上拉加载提示 -->
	<view class="loading-height">
		<Loading v-if="loading"></Loading>
	</view>
	<view style="height: 200rpx;"></view>

	<!-- 支付弹窗 -->
	<page-container :show="show" round="true" @clickoverlay="show = false">
		<view class="customStyle">
			<view class="container-guan">
				<image src="/static/images/close.svg" mode="widthFix" @click="show = false"></image>
			</view>
			<view class="container-price">
				<text>零食商城平台</text>
				<text>¥ {{total_price}}</text>
			</view>
			<view class="Payment-Methods">
				<text>支付方式</text>
				<text>零钱通</text>
			</view>
			<view class="Confirm-payment">
				<button type="primary" :loading="pay_loading" @click="confirmPay">确认支付</button>
			</view>
		</view>
	</page-container>

</template>

<script setup>
	import { reactive, toRefs, ref, onBeforeUnmount, watch } from 'vue'
	import { onLoad, onReachBottom } from '@dcloudio/uni-app'
	import Loading from "../../components/loading.vue"
	import { merchantNo, orderNo } from "../../public/package-js/orderNumber.js"
	import { Pay } from "@/public/package-js/pay.js"
	import { FeedBack } from "@/public/package-js/feedBack.js"
	import moment from 'moment'
	moment.locale('zh-cn');

	const data = reactive({
		tab: [ // tab 数据  query：查询条件
			{ name: '全部', query: {} },
			{ name: '待支付', query: { pay_status: 0 } },
			{ name: '待发货', query: { pay_status: 1, deliver_status: 0 } },
			{ name: '待收货', query: { pay_status: 1, deliver_status: 1 } },
			{ name: '待评价', query: { pay_status: 1, deliver_status: 2, evaluate: false } }
		],
		tabIndex: 0, // tab默认选择下标
		order_data: [], // 订单数据 
		loading: false, // 上拉提示小圆圈
		pageNum: 0, // 请求的页数，每请求一次，页数 +1

		total_price: 0, // 支付弹窗显示的总价
		show: false, // 控制支付弹窗
		pay_loading: false, // 控制支付按钮是否带 loading 图标
		pay_order: {}, // 继续支付的订单信息
		pay_index: -1, // 待支付展示的下标

		eav_id: '', // 点击评价的订单 id，用以更改订单状态

	})
	const { tab, tabIndex, order_data, loading, total_price, show, pay_loading } = toRefs(data)

	// 页面加载显示数据
	onLoad((event) => {
		console.log(event)
		let length = Object.keys(event).length // 判断是否有传值，没有的话默认展示全部订单
		let index = length === 0 ? 0 : JSON.parse(event.obj).index
		let query = length === 0 ? {} : JSON.parse(event.obj).query
		clickTab(index, query)
	})

	// 1、tab切换
	function clickTab(index, query) {
		data.tabIndex = index
		data.order_data = [] // 清空
		data.pageNum = 0
		let skip = data.pageNum * 10
		getData(skip, query)
	}

	// 2、请求数据
	const db = wx.cloud.database()
	async function getData(skip, query) {
		const user = uni.getStorageSync('user_info') //取出本地缓存的用户信息
		query['_openid'] = user.openid // 查询当前登录用户的订单信息
		// console.log("query",query);
		const res = await db.collection('order_data').where(query).limit(10).skip(skip).orderBy('order_time', 'desc').get()
		// console.log("res", res)

		// 考虑到上拉加载
		data.order_data = [...data.order_data, ...res.data]
	}


	// 3、上拉加载
	onReachBottom(async () => { //onReachBottom只能在父组件才能触底
		data.loading = true
		data.pageNum++
		let skip = data.pageNum * 10
		let query = data.tab[data.tabIndex].query
		await getData(skip, query)
		data.loading = false
	})

	// 4、待支付订单相关操作
	// 点击待支付
	async function continuePay(item, index) {
		console.log("item", item);
		data.total_price = item.subtotal
		uni.showLoading({ title: '正在下单', mask: true })
		try {
			let merchant_no = merchantNo()
			data.pay_order = item
			data.pay_index = index

			// 弹出支付弹窗
			uni.hideLoading()
			data.show = true
		} catch (err) {
			// 支付发生错误
			new FeedBack('支付发生错误', 'error').toast()
		}
	}

	// 确认支付
	async function confirmPay() {
		data.pay_loading = true
		const user = uni.getStorageSync('user_info') //取出本地缓存的用户信息

		// 当前时间:年月日，时分秒(下单时间)
		let order_time = moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
		// 当前时间：年月日(用于商家查询)
		let query_time = moment().utcOffset(8).format('YYYY-MM-DD')

		// 更新该条数据的某些字段
		await db.collection('order_data').where({
			_openid: user.openid,
			_id: data.pay_order._id
		}).update({
			data: {
				pay_status: 1, // 支付成功
				merchant_no: data.pay_order.merchant_no,
				order_time,
				query_time
			}
		})

		//支付成功：库存自减，售出自增
		await new Pay().setStock([data.pay_order])

		// 如果 tab 切换在全部上，就更改按钮，否则就将该订单从当前页面移除掉，减少请求次数
		if (data.tabIndex == 0) {
			data.order_data[data.pay_index].pay_status = 1
		} else {
			data.order_data.splice(data.pay_index, 1)
		}
		data.pay_loading = false
		data.show = false
	}

	// 5、取消订单
	async function cancelOrder(item, index) {
		const user = uni.getStorageSync('user_info') //取出本地缓存的用户信息
		await db.collection('order_data').where({
			_openid: user.openid,
			_id: item._id
		}).update({
			data: { pay_status: 2 }
		})

		// 如果tab切换在全部上，就更改状态，否则就移除掉
		if (data.tabIndex == 0) {
			data.order_data[index].pay_status = 2
		} else {
			data.order_data.splice(index, 1)
		}
	}

	// 6、申请退款
	let itemList = ['七天无理由退换货', '商品信息描述不符', '质量问题', '包装/商品破损/污渍']

	function applyRefund(item, index) {
		// 操作菜单
		uni.showActionSheet({
			alertText: '退款原因',
			itemList: itemList,
			success: async (res) => {
				const user = uni.getStorageSync('user_info') //取出本地缓存的用户信息
				await db.collection('order_data').where({
					_openid: user.openid,
					_id: item._id
				}).update({
					data: {
						deliver_status: 3,
						refund_reason: itemList[res.tapIndex],
						order_time: moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
					}
				})
				// 如果tab切换在全部上，就更改状态，否则就移除掉
				if (data.tabIndex == 0) {
					data.order_data[index].deliver_status = 3
				} else {
					data.order_data.splice(index, 1)
				}
			},
			fail(res) {
				console.log(res.errMsg)
			}
		})
	}

	// 7、确认收货
	async function confirmReceive(item, index) {
		const user = uni.getStorageSync('user_info') //取出本地缓存的用户信息
		await db.collection('order_data').where({
			_openid: user.openid,
			_id: item._id
		}).update({
			data: { deliver_status: 2 }
		})
		// 如果tab切换在全部上，就更改状态，否则就移除掉 
		if (data.tabIndex == 0) {
			data.order_data[index].deliver_status = 2
		} else {
			data.order_data.splice(index, 1)
		}
	}

	// 8、去评价
	function goEavluate(item, index) {
		// console.log("item",item);
		if (item.evaluate) return false

		data.eav_id = item._id

		let res = JSON.stringify({
			goods_id: item.goods_id,
			index: index,
			specs: item.specs,
			goods_image: item.goods_image
		})
		uni.navigateTo({
			url: '/pages/good-evaluation/good-evaluation?data=' + res
		})
	}

	// 9、监听提交评价后更改当前界面某订单的状态
	import { order_eva_index } from "@/public/package-js/passValue.js"
	watch(order_eva_index, (newVal, oldVal) => {
		// console.log("newVal",newVal);
		// console.log("data",data);

		// 如果tab切换在全部上，就更改状态，否则就移除掉
		if (data.tabIndex == 0) {
			data.order_data[newVal].evaluate = true
		} else {
			data.order_data.splice(newVal, 1)
		}
		const user = uni.getStorageSync('user_info') //取出本地缓存的用户信息
		db.collection('order_data').where({
			_openid: user.openid,
			_id: data.eav_id
		}).update({ data: { evaluate: true } })
	})

	// 10、查看物流
	function goTracking(item) {
		// console.log(item);
		let obj = JSON.stringify({
			waybill_No: item.waybill_No,
			goods_image: item.goods_image,
			goods_title: item.goods_title,
			buy_amount: item.buy_amount
		})
		uni.navigateTo({
			url: '/pages/order-tracking/order-tracking?data=' + obj
		})
	}

	// onBeforeUnmount(() => { data.show= false })
</script>

<style lang="less">
	page {
		background-color: #f8f8f8;
	}

	.order-tab {
		height: 60rpx;
		background-color: #FFFFFF;
		display: flex;
		justify-content: space-around;
		color: #737373;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
	}

	.order-tab view {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	.order-select {
		display: block;
		width: 40rpx;
		height: 10rpx;
		border-radius: 50rpx;
		background-color: #ea4050;
		position: absolute;
		bottom: 0;
	}

	/* 订单卡片 */
	.order-back {
		background-color: #fefefe;
		padding: 20rpx;
		margin: 20rpx 10rpx;
		border-radius: 10rpx;
	}

	/* 订单编号部分 */
	.order-top {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #d6d6d6;

		text {
			font-size: 28rpx;
		}

		&>text:nth-child(1) {
			color: #6f7073;
		}

		&>text:nth-child(2) {
			color: red;
		}
	}

	/* 订单编号部分 */
	.order-top {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #d6d6d6;

		text {
			font-size: 28rpx;
		}

		&>text:nth-child(1) {
			color: #6f7073;
		}

		&>text:nth-child(2) {
			color: red;
		}
	}


	.order-card image {
		width: 150rpx;
		height: 150rpx;
		display: block;
		border-radius: 8rpx;
	}

	.order-card {
		display: flex;
	}

	.order-card view:nth-child(2) {
		flex: 1;
		padding: 0 20rpx;
	}

	.order-title-padding {
		margin-bottom: 20rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}

	.order-specs {
		background-color: #fafafa;
		font-size: 27rpx;
		color: #767676;
		padding: 10rpx;
		border-radius: 9rpx;
	}

	.order-num {
		color: #8b8c90;
	}
	
	// 退款理由 + 合计
	.order-total{
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
	}
	
	.order-refund{
		color: #ea506c;
		font-size: 28rpx;
	}

	/* 合计 */
	.order-subtotal {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		margin-bottom: 30rpx;
	}

	.order-subtotal text {
		display: block;
		padding-left: 10rpx;
	}

	.order-subtotal text:nth-child(1) {
		color: #8b8c90;
	}

	.order-subtotal text:nth-child(2) {
		font-weight: bold;
		font-size: 34rpx;
	}

	/* 按钮 */
	.order-button {
		display: flex;
		justify-content: flex-end;
	}

	.order-button text {
		padding: 15rpx 35rpx;
		margin-left: 20rpx;
		border-radius: 10rpx;
	}

	.order-button-a {
		border: 1rpx solid #d7d8d8;
		color: #8b8c90;
	}

	.order-button-b {
		background-color: #ea4050;
		color: #FFFFFF;
	}
</style>
